package com.nsi.util;

import org.apache.commons.io.IOUtils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

/**
 * 微信发送Https请求
 */
public class Httpsrequest {

    /**
     * Https 请求
     *
     * @param requestUrl    URL
     * @param requestMethod 方法get/post
     * @param param         参数
     * @return
     * @throws Exception
     */
    public static String httpsRequest(String requestUrl, String requestMethod, String param) throws Exception {
        // 创建SSL连接
        SSLSocketFactory ssf = getSslSocketFactory();
        //设置当前实例使用sslSOCKETfactory
        HttpsURLConnection conn = getHttpsURLConnection(requestUrl, requestMethod, param, ssf);
        // 返回响应内容
        String bufferContent = getStringBuffer(conn);
        return bufferContent;
    }


    /**
     * Https 请求
     *
     * @param requestUrl    URL
     * @param requestMethod 方法get/post
     * @param param         参数
     * @return
     * @throws Exception
     */
    public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String param) throws Exception {
        // 创建SSL连接
        SSLSocketFactory ssf = getSslSocketFactory();
        //设置当前实例使用sslSOCKETfactory
        HttpsURLConnection conn = getHttpsURLConnection(requestUrl, requestMethod, param, ssf);
        // 返回响应内容
//        String bufferContent = getStringBuffer(conn);
        byte[] byteBuffer = getByteBuffer(conn);
        return byteBuffer;
    }


    /**
     * 发送文件请求
     *
     * @param requestUrl
     * @param requestMethod
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static String httpsRequestFile(String requestUrl, String requestMethod, InputStream inputStream) throws Exception {

        //创建SSLContext
        SSLSocketFactory ssf = getSslSocketFactory();
        //设置当前实例使用sslSOCKETfactory
        HttpsURLConnection conn = getHttpsURLConnection(requestUrl, requestMethod, inputStream, ssf);
        String bufferContent = getStringBuffer(conn);

        //打印数据
        return bufferContent;
    }


    /**
     * 返回内容
     *
     * @param conn
     * @return
     * @throws IOException
     */
    private static byte[] getByteBuffer(HttpsURLConnection conn) throws IOException {

        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while((rc=is.read(buff, 0, 100))>0) {
            baos.write(buff, 0, rc);
        }
        return baos.toByteArray();
    }


    /**
     * 返回内容
     *
     * @param conn
     * @return
     * @throws IOException
     */
    private static String getStringBuffer(HttpsURLConnection conn) throws IOException {
        StringBuffer buffer;
        //读取服务端的内容
        InputStream is = conn.getInputStream();
        InputStreamReader isr = new InputStreamReader(is, "utf-8");
        BufferedReader br = new BufferedReader(isr);
        buffer = new StringBuffer();
        String line = null;
        while ((line = br.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();
    }


    /**
     * 发送请求
     *
     * @param requestUrl
     * @param requestMethod
     * @param outStr
     * @param ssf
     * @return
     * @throws IOException
     */
    private static HttpsURLConnection getHttpsURLConnection(String requestUrl, String requestMethod, String outStr, SSLSocketFactory ssf) throws IOException {
        StringBuffer buffer = null;
        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(requestMethod);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setSSLSocketFactory(ssf);
        conn.connect();
        if (outStr != null) {
            OutputStream os = conn.getOutputStream();
            os.write(outStr.getBytes("UTF-8"));
            os.close();
        }
        return conn;
    }

    /**
     * 获取SSLSocketFactory 对象
     *
     * @return
     * @throws NoSuchAlgorithmException
     * @throws NoSuchProviderException
     * @throws KeyManagementException
     */
    private static SSLSocketFactory getSslSocketFactory() throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
        //创建SSLContext
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        TrustManager[] tm = {new MyX509TrustManager()};
        //初始化
        sslContext.init(null, tm, new java.security.SecureRandom());
        //获取sslSOCKETfactory对象
        return sslContext.getSocketFactory();
    }


    /**
     * 建立文件连接
     *
     * @param requestUrl
     * @param requestMethod
     * @param inputStream
     * @param ssf
     * @return
     * @throws IOException
     */
    private static HttpsURLConnection getHttpsURLConnection(String requestUrl, String requestMethod, InputStream inputStream, SSLSocketFactory ssf) throws IOException {
        StringBuffer buffer = null;
        URL url = new URL(requestUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod(requestMethod);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setSSLSocketFactory(ssf);
        conn.setRequestProperty("Content-Disposition", "form-data;name=\"media\";filename=\"a.jpg\"");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        conn.connect();
        if (inputStream != null) {
            OutputStream os = conn.getOutputStream();
            os.write(IOUtils.toByteArray(inputStream));
            os.close();
        }
        return conn;
    }


}
